/-app
TopLayout.ts
main.css
start.ts
/-docs ...
/-docs/types ...
text.ts
api.ts
/-files
/-imports
/-storage
/-typings
codemirror.d.ts
knockout.d.ts
websql.d.ts
errors.js
functions.ts
index.html
try.js
xxxxxxxxxx
 
9
  export class TextDocumentHandler implements DocumentHandler {
10
​
11
    private _doc: CodeMirror.Doc = null;
12
    private _text: string = null;
13
    private _editor: { cm: CodeMirror; host: HTMLElement; } = null;
14
    private _saveTimer = new Timer();
15
​
16
    constructor(
17
      private _read: (property: string) => string,
18
      private _write: (property: string, content: string) => void) {
19
      this._saveTimer.ontick = () => this.save();
20
    }
21
    
22
    getText() {
23
      if (this._text === null) {
24
        if (this._doc)
25
          this._text = this._doc.getValue();
26
        else
27
          this._text = this._read(null);
28
      }
29
      return this._text;
30
    }
31
    
32
    getDoc() {
33
      if (!this._doc) {
34
        this._doc = new CodeMirror.Doc(this.getText());
35
        CodeMirror.on(this._doc, 'change', (instance, changeObj) => this._onDocChange(changeObj));
36
      }
37
      return this._doc;
38
    }
39
​
40
    open(): HTMLElement {
41
​
42
      return this._getEditor().host;
43
      
44
    }
45
​
46
    close() {
47
      this._saveTimer.endWaiting();
48
      if (this._editor) {
49
        var e = this._editor;
50
        this._editor = null;
51
        returnEditor(e);
52
      }
53
    }
54
    
55
    save() {
56
      this._write(null, this.getText());
57
    }
58
​
59
    private _getEditor() {
60
      if (!this._editor) { 
61
        this._editor = requestEditor();
62
        this._editor.cm.swapDoc(this.getDoc());
63
      }
64
      return this._editor;
65
    }
66
    
67
    private _onDocChange(changeObj: CodeMirror.EditorChange) {
68
      this._saveTimer.reset();
69
    }
70
    
71
  }
72
  
73
  var editorCache: { cm: CodeMirror; host: HTMLElement; } [] = [];
74
​
75
  function requestEditor(): { cm: CodeMirror; host: HTMLElement; } {
76
    if (editorCache.length)
77
      return editorCache.pop();
78
    
79
    var host: HTMLElement = null;
80
    var cm = new CodeMirror(_host => host = _host);
81
    
82
    return { cm: cm, host: host };
83
  }
84
  
85
  function returnEditor(editor: { cm: CodeMirror; host: HTMLElement; }) {
86
    editorCache.push(editor);
87
  }
88
  
89
}
61:47